package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.aiassistant.domain.entity.AiPaymentEntity;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.wrap.EnableApiCallBack;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ApiCallBackEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.fund.enums.ModelTypeEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.dao.PaymentDao;
import com.xbongbong.saas.domain.entity.ext.PaymentEntityExt;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.PaymentLinkTypeEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.RefundInstockEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.FundSetModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSubDataModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/1/25 15:28
 * @since v1.0
 */
@Service("paymentModel")
public class PaymentModelImpl implements PaymentModel {

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaymentDao paymentDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private PaymentSubDataModel paymentSubDataModel;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private FundSetModel fundSetModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PAYMENT, operateTypeEnum = OperateTypeEnum.NEW)
    public Integer insert(PaymentEntityExt entity) throws XbbException {
        //TODO  先进行数据库的插入动作
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = paymentDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        return success;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PAYMENT, operateTypeEnum = OperateTypeEnum.NEW, isBatch = true)
    public List<PaymentEntityExt> insertBatch(List<PaymentEntityExt> list) throws XbbException{
        for (PaymentEntityExt paymentEntityExt : list) {
            paasFormSubDataModel.transferSubForm(paymentEntityExt, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        }
        StandardizeDataUtil.standardize4EntityList(list);
        paymentDao.insertBatch(list);
        //ES数据插入
        List<InsertDTO> insertList = new ArrayList<>();
        for (PaymentEntityExt item : list) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
            insertDTO.setEsId(item.getCorpid() + "_" + item.getId());
            item.setDataId(item.getId());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(item, paasFormDataEntity);
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT);
            insertList.add(insertDTO);
        }
        paasEsModel.insertBatch(insertList);

        paasFormSubDataModel.insertBatchSubFormData(list, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        return list;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PAYMENT, operateTypeEnum = OperateTypeEnum.EDIT)
    public Integer update(PaymentEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer integer = paymentDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity, false);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT);
        insertDTO.getSource().remove("creatorId");
        paasEsModel.update(insertDTO);

        paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PAYMENT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = paymentDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PAYMENT);
        }
        if (!subList.isEmpty()) {
            paymentSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public void savePaymentPlan(String corpid, List<UpdateDataEntity> updateList) throws XbbException {
        try {
            if (CollectionsUtil.isNotEmpty(updateList)) {
                updateBatch(updateList, corpid);
            }
        } catch (Exception e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PAYMENT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = paymentDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PAYMENT, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            paymentSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PAYMENT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid,boolean needThrow) throws XbbException{
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        // 3. 更新主表
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = paymentDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_PAYMENT,needThrow);
        }

        if (!subList.isEmpty()) {
            paymentSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public List<PaymentEntityExt> findEntitys(Map<String, Object> param) {
        List<PaymentEntityExt> entitys = paymentDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return paymentDao.getEntitysCount(param);
    }

    @Override
    public Integer save(PaymentEntityExt paymentEntity) throws XbbException {
        return null;
    }

    @Override
    public PaymentEntityExt getByKey(Long key, String corpid) {
        PaymentEntityExt paymentEntityExt = paymentDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(paymentEntityExt), IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        return paymentEntityExt;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PAYMENT, operateTypeEnum = OperateTypeEnum.DELETE, isBatch = true)
    public Integer deleteBatch(List<Long> list, String corpid, Integer del) throws XbbException {
        Integer integer = paymentDao.deleteBatch(list, corpid);
        //ES根据id批量设置del=1
        paasEsModel.deleteBatch(list, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_PAYMENT);
        paasFormSubDataModel.deleteBatchByDataId(list, corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public List<PaymentEntityExt> getPaymentRemindByContractId(String corpid, List<Long> contractIds, Long startTime, Long endTime) {
        List<PaymentEntityExt> paymentEntityExts = paymentDao.getPaymentRemindBycontractId(corpid, contractIds, startTime, endTime);
        paasFormSubDataModel.findSubEntity(corpid, paymentEntityExts, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        return paymentEntityExts;
    }


    @Override
    public List<PaymentEntityExt> getPaymentOverdueByContractId(String corpid, List<Long> contractIds, Long startEstimateTime, Long endEstimateTime) {
        List<PaymentEntityExt> paymentEntityExts = paymentDao.getPaymentRemindBycontractId(corpid, contractIds, startEstimateTime, endEstimateTime);
        paasFormSubDataModel.findSubEntity(corpid, paymentEntityExts, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        return paymentEntityExts;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PAYMENT, operateTypeEnum = OperateTypeEnum.DELETE)
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT);
        paasEsModel.delete(deleteDTO);
        Integer integer = paymentDao.deleteByKey(key, corpid);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        return integer;
    }

    @Override
    @EnableApiCallBack(callBackBusiness = ApiCallBackEnum.PAYMENT, operateTypeEnum = OperateTypeEnum.EDIT, isBatch = true)
    public Integer updateBatchForData(List<? extends PaasFormDataEntity> updateList, String corpid) throws XbbException {
        for (PaasFormDataEntity paasFormDataEntityExt : updateList) {
            paasFormSubDataModel.transferSubForm(paasFormDataEntityExt, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        }
        StandardizeDataUtil.standardize4EntityList(updateList);
        Integer updateCount = paymentDao.updateBatchForAll(updateList,corpid);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity entityExt : updateList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid+"_"+entityExt.getId());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entityExt, paasFormDataEntity);
            paasFormDataEntity.setDataId(entityExt.getId());
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList);
        // TODO: 2020/9/22

        return updateCount;
    }
    
    /**
     * 根据合同编号,获取付款单ID
     *
     * @param corpid
     * @param contractId
     * @author chenshan
     * @Date 2019-11-07 15:06
     */
    @Override
    public List<Long> getPaymentByContractId(String corpid, Long contractId) {
        return paymentDao.getPaymentByContractId(corpid,contractId);
    }

    @Override
    public List<PaymentEntityExt> getPaymentEntityByContractId(String corpid, Long contractId) {
        List<PaymentEntityExt> paymentEntityExts = paymentDao.getPaymentEntityByContractId(corpid, contractId);
        paasFormSubDataModel.findSubEntity(corpid, paymentEntityExts, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        return paymentEntityExts;
    }
    
    @Override
    public List<PaymentEntityExt> getRedPaymentList(String corpid) {
        List<PaymentEntityExt> paymentList = paymentDao.getRedPaymentList(corpid);
        paasFormSubDataModel.findSubEntity(corpid, paymentList, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        return paymentList;
    }

    @Override
    public List<AiPaymentEntity> getPaymentList4Ai(String corpid, List<Long> idIn) {
        return paymentDao.getPaymentList4Ai(corpid, idIn);
    }

    @Override
    public List<PaymentEntityExt> getPaymentByIdIn(String corpid,List<Long> idIn){
        List<PaymentEntityExt> paymentEntityExts = paymentDao.getPaymentByIdIn(corpid, idIn);
        paasFormSubDataModel.findSubEntity(corpid, paymentEntityExts, IndexTypeEnum.IDX_SAAS_PAYMENT_SUB);
        return paymentEntityExts;
    }

    @Override
    public List<PaymentEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return paymentDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
        JSONObject jsonObject = dataEntity.getData();
        Integer type = FastJsonHelper.getIntegerOrDefaultFromFormData(jsonObject, PaymentEnum.REF_TYPE.getAttr(), PaymentLinkTypeEnum.CONTRACT.getCode());
        String status = FastJsonHelper.getStringOrDefaultFromFormData(jsonObject, PaymentEnum.STATUS.getAttr(), "");
        Integer isRed = FastJsonHelper.getIntegerOrDefaultFromFormData(jsonObject, PaymentEnum.RECEIVABLE_IS_RED.getAttr(), BasicConstant.ONE);
        //获取开票金额
        Double invoiceAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(jsonObject, PaymentEnum.INVOICE_AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
        boolean isRedReceivables = Objects.equals(status, PaymentStatusEnum.RED_RECEIVABLES.getCode()) && Objects.equals(isRed, BasicConstant.ONE);
        Long modelType = dataEntity.getSysLong10();
        Long nowModelType = fundSetModel.getModelType(formatExplainDTO.getCorpid(),XbbRefTypeEnum.CRM);
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        //旧逻辑，代码优化，状态判断从循环内提出 - by腾伟、zcp
        boolean unReceivables = Objects.equals(status, PaymentStatusEnum.UN_RECEIVABLES.getCode());
        if (CollectionsUtil.isNotEmpty(explainList)) {
            Iterator<FieldAttrEntity> iterator = explainList.iterator();
            while (iterator.hasNext()) {
                FieldAttrEntity fieldAttrEntity = iterator.next();
                String attr = fieldAttrEntity.getAttr();
                if (unReceivables && Objects.equals(attr, PaymentEnum.STATUS.getAttr())) {
                    fieldAttrEntity.getItems().removeIf(item -> Objects.equals(item.getShowType(), ShowTypeEnum.EXCLUDE_NEW.getCode()));
                }
                if (PaymentEnum.disableEdit(attr)) {
                    fieldAttrEntity.setEditable(0);
                }
                if (Objects.equals(type, PaymentLinkTypeEnum.REFUND.getCode()) && Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.CONTRACT.getAttr())) {
                    fieldAttrEntity.setLinkedType(type);
                    fieldAttrEntity.setAttrName(RefundInstockEnum.REF_ID.getAttrName());
                } else if (isRedReceivables && Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.RECEIVABLES_ORIGIN_ID.getAttr())) {
                    // 编辑红冲应收金额的时候，关联原始单据显示。编辑应收款的时候，关联原始单据不显示
                    fieldAttrEntity.setVisible(BasicConstant.ONE);
                    fieldAttrEntity.setShowType(ShowTypeEnum.EDIT_DETAIL.getCode());
                    fieldAttrEntity.setLinkedType(XbbRefTypeEnum.PAYMENT.getCode());
                } else if (Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.ESTIMATE_TIME.getAttr())) {
                    //只有状态是未收款或部分未收款、并且处于手动创建应收模式、并且是手动创建应收模式下产生的应收款数据，才允许修改预计回款日期；其他所有情况都不允许修改
                    boolean flag = PaymentStatusEnum.getPaymentUnEditStatus().contains(status) || !Objects.equals(nowModelType, ModelTypeEnum.PLAN.getCode()) || (Objects.nonNull(modelType) && !Objects.equals(modelType, ModelTypeEnum.PLAN.getCode()));
                    if (flag) {
                        fieldAttrEntity.setEditable(BasicConstant.ZERO);
                    }
                } else if (Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.AMOUNT.getAttr())) {
                    //只有状态是未收款、并且处于手动创建应收模式、并且开票金额为0，并且是手动创建应收模式下产生的应收款数据，才允许次修改应收金额；其他所有情况都不允许修改
                    boolean flag = !PaymentStatusEnum.checkPaymentEditStatus(status)
                            || !Objects.equals(nowModelType, ModelTypeEnum.PLAN.getCode())
                            || (Objects.nonNull(modelType) && !Objects.equals(modelType, ModelTypeEnum.PLAN.getCode()))
                            || !Objects.equals(invoiceAmount,BasicConstant.ZERO_DOUBLE);
                    if (flag) {
                        fieldAttrEntity.setEditable(BasicConstant.ZERO);
                    }
                }else if (Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.ADD_PAYMENT.getAttr())) {
                    iterator.remove();
                }else if ((Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.OWNER_ID.getAttr()) ||
                Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.COUSERID.getAttr())) && !PaymentStatusEnum.checkPaymentEditStatus(status)) {
                    fieldAttrEntity.setEditable(BasicConstant.ZERO);
                }
            }
        }
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param formDataUpdateGetDTO saas编辑数据
     * @param result               要返回的jsonObject
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/22 15:28
     */
    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, PaymentEnum.CUSTOMER.getAttr(), PaymentEnum.CUSTOMER_LINK_TEXT.getAttr(), PaymentEnum.CUSTOMER.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PaymentEnum.CONTRACT.getAttr(), PaymentEnum.CONTRACT_LINK_TEXT.getAttr(), PaymentEnum.CONTRACT.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PaymentEnum.SOURCE.getAttr(), PaymentEnum.SOURCE_LINK_TEXT.getAttr(),PaymentEnum.SOURCE.getFieldType());
        double businessType = FastJsonHelper.getDoubleOrDefaultFromFormData(result, PaymentEnum.SOURCE_REF_TYPE.getAttr(), 0d);
        if (XbbRefTypeEnum.PAYMENT_TASK.getCode() == businessType) {
            JSONArray jsonArray = result.getJSONArray(PaymentEnum.SOURCE.getAttr());
            if (Objects.nonNull(jsonArray) && jsonArray.size() > 0) {
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                jsonObject.put(BasicConstant.BUSINESS_TYPE, XbbRefTypeEnum.PAYMENT_TASK.getCode());
            }
        }else if (XbbRefTypeEnum.INVOICE.getCode()== businessType) {
            JSONArray jsonArray = result.getJSONArray(PaymentEnum.SOURCE.getAttr());
            if (Objects.nonNull(jsonArray) && jsonArray.size() > 0) {
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                jsonObject.put(BasicConstant.BUSINESS_TYPE, XbbRefTypeEnum.INVOICE.getCode());
            }
        }else if (XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()== businessType) {
            JSONArray jsonArray = result.getJSONArray(PaymentEnum.SOURCE.getAttr());
            if (Objects.nonNull(jsonArray) && jsonArray.size() > 0) {
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                jsonObject.put(BasicConstant.BUSINESS_TYPE, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode());
            }
        }
        showFormatHelp.formatLinkBusiness4Show(result, PaymentEnum.RECEIVABLES_ORIGIN_ID.getAttr(), PaymentEnum.RECEIVABLES_ORIGIN_LINK_TEXT.getAttr(),PaymentEnum.RECEIVABLES_ORIGIN_ID.getFieldType());
    }


    /**
     * 获取最大id，用于迁移脚本时候记录进度所用
     *
     * @param param
     * @return
     */
    @Override
    public Long getMaxId(Map<String, Object> param) {
        return paymentDao.getMaxId(param);
    }

    @Override
    public void updateBatchAll(List<PaymentEntityExt> paymentEntityExts) throws XbbException {
        StandardizeDataUtil.standardize4EntityList(paymentEntityExts);
        paymentDao.updateBatchAll(paymentEntityExts);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaymentEntityExt entityExt : paymentEntityExts){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(entityExt.getCorpid()+"_"+entityExt.getId());
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entityExt, paasFormDataEntity);
            paasFormDataEntity.setDataId(entityExt.getId());
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYMENT);
            insertDTOList.add(insertDTO);
        }
        //默认不抛出
        paasEsModel.updateBatch(insertDTOList, WriteRequest.RefreshPolicy.WAIT_UNTIL, false);
    }

    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = paymentDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYMENT);
        paasEsModel.update(insertDTO);
        return success;
    }

    @Override
    public <T> List<T> getPaymentEsDataListByLinkId(String corpid, Long linkId, PaymentEnum paymentEnum, Class<T> clazz) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(PaymentEnum.getEsAttr4Keyword(paymentEnum), linkId));
        boolQueryBuilder.filter(termQuery("del", 0));
        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PAYMENT.getType()));
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PAYMENT.getIndex());
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 0, PaasConstant.ES_MAX_PAGE_SIZE);
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<T> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, clazz);
        return esEntities.getContent();
    }
}
